# -*- coding: utf-8 -*-
from models import *
from django import forms
from django.contrib.localflavor.br.forms import BRCPFField, BRCNPJField, BRPhoneNumberField, BRZipCodeField
from django.utils.safestring import mark_safe
from django.forms.widgets import CheckboxSelectMultiple,RadioSelect
from ajax_select import make_ajax_form
from django.forms.util import ErrorList

class HorizRadioRenderer(forms.RadioSelect.renderer):
    def render(self):
        return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class FornecedorForm(forms.ModelForm):
    class Meta:
        model = Fornecedor
    cnpj = BRCNPJField(label = ('CNPJ'),required=False,widget=forms.TextInput(attrs={'alt':"cnpj"}))
    cep = BRZipCodeField(widget=forms.TextInput(attrs={'alt':'cep'}))
    telefone = BRPhoneNumberField(widget=forms.TextInput(attrs={'alt':'phone'}))
    tipo = forms.ModelMultipleChoiceField(label=('Filiação'),queryset=Tipo_Empresa.objects.all(), widget=CheckboxSelectMultiple(attrs={'class':'validate[required]'}))
    cpf = BRCPFField(label = ('CPF'),required=False,widget=forms.TextInput(attrs={'alt':"cpf"}))
    pessoa = forms.ChoiceField(widget=RadioSelect(renderer=HorizRadioRenderer, attrs={'class':'validate[required]'}), choices=PESSOA_C,initial=0)
    comissao = forms.DecimalField(label=('Comissão %'),required=False, widget=forms.TextInput(attrs={'alt':"money-db"}))
    limitecompra = forms.DecimalField(label=('Limite da Compra R$'), required=False, widget=forms.TextInput(attrs={'alt':"money-db"}))
    tabelaprecovenda = forms.DecimalField(label=('Acressimo na tabela de preço %'), required=False, widget=forms.TextInput(attrs={'alt':"money-db"}))

    def clean(self):
        cn = self.cleaned_data
        cnp = self.cleaned_data.get("cnpj")
        pes = self.cleaned_data.get("pessoa")
        cp = self.cleaned_data.get("cpf")
        msg = u"Este campo é obrigatório."

        if "0" in pes:
            if cnp == "":
                self._errors["cnpj"] = ErrorList([msg])
        if "1" in pes:
            if cp == "":
                self._errors["cpf"] = ErrorList([msg])

        return self.cleaned_data


class RevendaForm(forms.ModelForm):
    class Meta:
        model = Revenda
    vendedor = forms.ModelChoiceField(queryset = Fornecedor.objects.filter(tipo__id__icontains = 1))

class ContatoForm(forms.ModelForm):
    class Meta:
        model = Contatos
    telefoneresponsavel = BRPhoneNumberField(label=('Telefone'),widget=forms.TextInput(attrs={'alt':'phone'}), required= False)
    aniversario = forms.DateField(widget=forms.TextInput(attrs={'alt':"date"}), required=False)

class VendeForm(forms.ModelForm):
    class Meta:
        model = CompraProdutoVendedor
        form = make_ajax_form(CompraProdutoVendedor,{'produtofornecedor':'produto'})
    quantidade = forms.IntegerField(label=('Chupa'))
